import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isNil from "lodash/isNil";

var _dec, _dec2, _dec3, _dec4, _dec5, _class2, _class3;

import React from 'react';
import { Form, Modal, Input, Row, Col, List, Dropdown, Menu, Icon } from 'antd';
import intl from 'utils/intl';
import { Bind } from 'lodash-decorators';
import styles from "./index.less?modules";
var ListItem = List.Item;
var MenuItem = Menu.Item;
var Meta = ListItem.Meta;
var FormItem = Form.Item;
var TextArea = Input.TextArea;
var htmlText = "<div class=\"demo-wrapper\" style=\"color: <%=u1.no === 1 ? 'red' : '#333' %>\";>\n    <%= u1.title%>\n</div>\n";
var defaultFieldList = [{
  unitFieldName: intl.get('cpfm.individual.common.none').d('无'),
  unitFieldCode: ''
}];
var defaultAliasList = {
  unitName: intl.get('cpfm.individual.common.context').d('上下文参数'),
  unitCode: 'context',
  alias: 'c'
};
var reg = /([_A-Za-z0-9]+)\.$/;
var toCamel = /(_)([a-z])/g;

var _class = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec(_class2 = (_class3 = /*#__PURE__*/function (_React$Component) {
  _inherits(_class3, _React$Component);

  var _super = _createSuper(_class3);

  function _class3(props) {
    var _this;

    _classCallCheck(this, _class3);

    _this = _super.call(this, props);
    var _props$unitList = props.unitList,
        unitList = _props$unitList === void 0 ? [] : _props$unitList,
        _props$unitAlias = props.unitAlias,
        unitAlias = _props$unitAlias === void 0 ? [] : _props$unitAlias,
        unitCode = props.unitCode;
    var unitAliasMap = new Map();
    var fieldsMap = new Map();
    unitAlias.forEach(function (i) {
      unitAliasMap.set(i.unitCode, i.alias);
    });
    unitList.forEach(function (i) {
      var alias = i.unitCode === unitCode ? 'self' : unitAliasMap.get(i.unitCode);

      if (alias !== undefined) {
        fieldsMap.set(alias, i.unitFields);
      }
    });
    fieldsMap.set('c', [{
      unitFieldName: intl.get('cpfm.customize.common.organizationId').d('采购方租户'),
      unitFieldCode: 'organizationId'
    }, {
      unitFieldName: intl.get('cpfm.customize.common.tenantId').d('供应商租户'),
      unitFieldCode: 'tenantId'
    }]);
    _this.state = {
      fieldList: defaultFieldList,
      left: 0,
      top: 0,
      insertPosition: -1,
      posReverseY: false,
      open: false,
      fieldsMap: fieldsMap
    };
    _this.hiddenDiv = React.createRef();
    return _this;
  }

  _createClass(_class3, [{
    key: "onOk",
    value: function onOk() {
      var _this$props = this.props,
          onOk = _this$props.onOk,
          onClose = _this$props.onClose,
          form = _this$props.form;
      form.validateFields(function (err, values) {
        if (!err) {
          // eslint-disable-next-line no-unused-expressions
          typeof onOk === 'function' && onOk(values); // eslint-disable-next-line no-unused-expressions

          typeof onClose === 'function' && onClose();
        }
      });
    }
  }, {
    key: "getAliasList",
    value: function getAliasList() {
      var _this$props2 = this.props,
          _this$props2$unitAlia = _this$props2.unitAlias,
          unitAlias = _this$props2$unitAlia === void 0 ? [] : _this$props2$unitAlia,
          unitCode = _this$props2.unitCode;
      var newAliasArray = unitAlias.concat([defaultAliasList]);
      var menu = /*#__PURE__*/React.createElement(Menu, {
        className: styles['unit-alias-list']
      }, newAliasArray.map(function (i) {
        return /*#__PURE__*/React.createElement(MenuItem, {
          className: "no-cursor",
          disabled: true
        }, /*#__PURE__*/React.createElement("div", {
          className: "unit-name"
        }, i.unitName), /*#__PURE__*/React.createElement("div", {
          className: "unit-code"
        }, i.unitCode), /*#__PURE__*/React.createElement("span", {
          className: "unit-alias"
        }, i.unitCode === unitCode ? 'self' : i.alias));
      }));
      return /*#__PURE__*/React.createElement(Dropdown, {
        className: "inc-title",
        overlay: menu,
        trigger: ['click']
      }, /*#__PURE__*/React.createElement("a", {
        className: "ant-dropdown-link"
      }, intl.get('cpfm.individual.view.message.title.aliasRefer').d('别名对照'), "\xA0", /*#__PURE__*/React.createElement(Icon, {
        type: "down"
      })));
    }
  }, {
    key: "onClickSyntax",
    value: function onClickSyntax() {
      var syntax = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      var form = this.props.form;
      var _this$textArea$textAr = this.textArea.textAreaRef,
          selectionStart = _this$textArea$textAr.selectionStart,
          selectionEnd = _this$textArea$textAr.selectionEnd;
      var originText = form.getFieldValue('renderRule') || '';
      var newText;

      if (selectionStart === undefined || selectionEnd === undefined) {
        newText = "".concat(originText).concat(syntax);
        form.setFieldsValue({
          renderRule: newText
        });
      } else {
        var leftText = originText.slice(0, selectionStart);
        var rightText = originText.slice(selectionEnd);
        form.setFieldsValue({
          renderRule: "".concat(leftText).concat(syntax).concat(rightText)
        });
      }

      this.textArea.textAreaRef.focus();
    }
  }, {
    key: "getSyntaxList",
    value: function getSyntaxList() {
      var _this2 = this;

      var menu = /*#__PURE__*/React.createElement(Menu, {
        className: styles['unit-alias-list'],
        onClick: function onClick(_ref) {
          var key = _ref.key;
          return _this2.onClickSyntax(key);
        }
      }, /*#__PURE__*/React.createElement(MenuItem, {
        key: '<%= u1.test %>'
      }, /*#__PURE__*/React.createElement("div", {
        className: "unit-name"
      }, intl.get('cpfm.individual.view.message.title.getVariable').d('获取变量')), /*#__PURE__*/React.createElement("div", {
        className: "unit-code"
      }, '<%= u1.test %>')), /*#__PURE__*/React.createElement(MenuItem, {
        key: '<%= var test = u1.test; %>'
      }, /*#__PURE__*/React.createElement("div", {
        className: "unit-name"
      }, intl.get('cpfm.individual.view.message.title.assignVariable').d('变量赋值')), /*#__PURE__*/React.createElement("div", {
        className: "unit-code"
      }, '<%= var test = u1.test; %>')), /*#__PURE__*/React.createElement(MenuItem, {
        key: "<%= u1.test = '1' ? true : false %>"
      }, /*#__PURE__*/React.createElement("div", {
        className: "unit-name"
      }, intl.get('cpfm.individual.view.message.title.thrExpression').d('三元表达式')), /*#__PURE__*/React.createElement("div", {
        className: "unit-code"
      }, "<%= u1.test = '1' ? true : false %>")), /*#__PURE__*/React.createElement(MenuItem, {
        key: '<% if (u1.v1) { %> ... <% } else if (u1.v2) { %> ... <% } %>'
      }, /*#__PURE__*/React.createElement("div", {
        className: "unit-name"
      }, intl.get('cpfm.individual.view.message.title.ifExpression').d('if-控制')), /*#__PURE__*/React.createElement("div", {
        className: "unit-code"
      }, '<% if (u1.v1) { %> ... <% } else if (u1.v2) { %> ... <% } %>')), /*#__PURE__*/React.createElement(MenuItem, {
        key: '<% for(var i = 0; i < u1.arr.length; i++){ %><%= i %> <%= u1.arr[i] %><% } %>'
      }, /*#__PURE__*/React.createElement("div", {
        className: "unit-name"
      }, intl.get('cpfm.individual.view.message.title.forExpression').d('for-循环')), /*#__PURE__*/React.createElement("div", {
        className: "unit-code"
      }, "<% for(var i = 0; i < u1.arr.length; i++){ %>\n                <%= i %> <%= u1.arr[i] %>\n              <% } %>")));
      return /*#__PURE__*/React.createElement(Dropdown, {
        className: "inc-title",
        overlay: menu,
        trigger: ['click']
      }, /*#__PURE__*/React.createElement("a", {
        className: "ant-dropdown-link"
      }, intl.get('cpfm.individual.view.message.title.syntaxRefer').d('语法对照'), "\xA0", /*#__PURE__*/React.createElement(Icon, {
        type: "down"
      })));
    }
  }, {
    key: "renderList",
    value: function renderList() {
      var _this$state = this.state,
          fieldList = _this$state.fieldList,
          _this$state$left = _this$state.left,
          left = _this$state$left === void 0 ? '50%' : _this$state$left,
          _this$state$top = _this$state.top,
          top = _this$state$top === void 0 ? '50%' : _this$state$top,
          open = _this$state.open,
          posReverseY = _this$state.posReverseY;
      return (
        /*#__PURE__*/
        // eslint-disable-next-line jsx-a11y/click-events-have-key-events
        React.createElement("ul", {
          onClick: this.fillFromTipsList,
          className: "".concat(styles['fields-tip'], " ").concat(open ? '' : styles.hidden),
          style: {
            left: left,
            top: top,
            transform: "translateY(".concat(posReverseY ? '-100%' : '0', ")")
          }
        }, fieldList.map(function (i) {
          return /*#__PURE__*/React.createElement("li", {
            value: i.unitFieldCode
          }, /*#__PURE__*/React.createElement("div", {
            className: "name"
          }, i.unitFieldName), /*#__PURE__*/React.createElement("div", {
            className: "code"
          }, i.unitFieldCode));
        }))
      );
    }
  }, {
    key: "openList",
    value: function openList(e) {
      var fieldsMap = this.state.fieldsMap;

      var _ref2 = e.target || {},
          selectionStart = _ref2.selectionStart,
          _ref2$value = _ref2.value,
          value = _ref2$value === void 0 ? '' : _ref2$value,
          scrollLeft = _ref2.scrollLeft,
          scrollTop = _ref2.scrollTop;

      var cacLengthStr = value.substring(0, selectionStart);
      var textGroupByLine = cacLengthStr.split('\n') || [''];
      var search = cacLengthStr.match(reg);

      if (!_isNil(search)) {
        var currentLine = textGroupByLine[textGroupByLine.length - 1];
        this.hiddenDiv.current.innerText = currentLine;
        var c1 = this.hiddenDiv.current.clientWidth;
        var visualHeight = textGroupByLine.length * 20 - scrollTop;
        var visualWidth = c1 - scrollLeft;
        var posReverseY = visualHeight >= 159;
        var posReverseX = visualWidth >= 445; // eslint-disable-next-line no-nested-ternary

        var scrollPosFixX = scrollLeft === 0 ? 0 : posReverseX ? -4 : 3;
        this.setState({
          left: posReverseX ? visualWidth - 150 + scrollPosFixX : visualWidth + scrollPosFixX,
          top: visualHeight,
          posReverseY: posReverseY,
          insertPosition: selectionStart,
          open: true,
          fieldList: fieldsMap.get(search[1]) || defaultFieldList
        });
      } else {
        this.setState({
          left: 0,
          top: 0,
          insertPosition: -1,
          open: false,
          posReverseY: false,
          fieldList: defaultFieldList
        });
      }
    }
  }, {
    key: "closeList",
    value: function closeList() {
      this.setState({
        left: 0,
        top: 0,
        insertPosition: -1,
        open: false,
        posReverseY: false,
        fieldList: defaultFieldList
      });
    }
  }, {
    key: "fillFromTipsList",
    value: function fillFromTipsList(e) {
      var form = this.props.form;
      var insertPosition = this.state.insertPosition;
      e.stopPropagation();
      var _e$nativeEvent$path = e.nativeEvent.path,
          path = _e$nativeEvent$path === void 0 ? [] : _e$nativeEvent$path;
      var li = path.find(function (i) {
        return i.nodeName === 'LI';
      });

      if (li) {
        var value = li.getAttribute('value').replace(toCamel, function (_, _1, $2) {
          return $2.toUpperCase();
        });
        var text = form.getFieldValue('renderRule');
        var leftText = text.slice(0, insertPosition);
        var rightText = text.slice(insertPosition);
        text = "".concat(leftText).concat(value).concat(rightText);
        form.setFieldsValue({
          renderRule: text
        });
        this.setState({
          left: 0,
          top: 0,
          insertPosition: -1,
          open: false
        });
        this.textArea.textAreaRef.focus();
        this.textArea.textAreaRef.setSelectionRange(text.length, text.length);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props3 = this.props,
          visible = _this$props3.visible,
          onClose = _this$props3.onClose,
          form = _this$props3.form,
          rule = _this$props3.rule;
      return /*#__PURE__*/React.createElement(Modal, {
        destroyOnClose: true,
        maskClosable: true,
        width: 1007,
        visible: visible,
        onCancel: onClose,
        onOk: this.onOk,
        bodyStyle: {
          padding: '16px 24px'
        },
        className: styles['compute-modal-container'],
        title: intl.get('cpfm.individual.view.message.title.virtualConfig').d('计算规则配置')
      }, /*#__PURE__*/React.createElement(Row, {
        gutter: 12
      }, /*#__PURE__*/React.createElement(Col, {
        span: 8
      }, /*#__PURE__*/React.createElement("div", {
        className: styles.title,
        style: {
          marginBottom: '8px'
        }
      }, intl.get('cpfm.individual.view.message.title.configInc').d('配置说明')), /*#__PURE__*/React.createElement(List, {
        itemLayout: "horizontal",
        style: {
          height: '342px',
          overflow: 'auto'
        }
      }, /*#__PURE__*/React.createElement(ListItem, null, /*#__PURE__*/React.createElement(Meta, {
        title: /*#__PURE__*/React.createElement("div", {
          className: styles['config-inc']
        }, /*#__PURE__*/React.createElement("span", {
          className: "inc-title"
        }, intl.get('cpfm.individual.view.message.tips.title1').d('在规则中使用表达式')), this.getSyntaxList()),
        description: intl.get('cpfm.individual.view.message.tips.desc1').d('规则代码中可以在任意位置使用‘<%= 表达式 %>’进行表达时运算')
      })), /*#__PURE__*/React.createElement(ListItem, null, /*#__PURE__*/React.createElement(Meta, {
        title: /*#__PURE__*/React.createElement("div", {
          className: styles['config-inc']
        }, /*#__PURE__*/React.createElement("span", {
          className: "inc-title"
        }, intl.get('cpfm.individual.view.message.tips.title2').d('获取字段')), this.getAliasList()),
        description: intl.get('cpfm.individual.view.message.tips.desc2').d('若当前单元设置了关联单元，可通过‘单元别名.单元字段’的方式获取，如：u1.rfxTitle （输入‘u1.’会自动提示单元中存在的字段，点击可自动补全）；表单、表格和查询类型默认关联当前单元，固定使用别名‘self’。\n目前上下文参数支持origanizationId-采购方租户和tenantId-供应商租户，通过别名‘c’获取.')
      })))), /*#__PURE__*/React.createElement(Col, {
        span: 16
      }, /*#__PURE__*/React.createElement("div", {
        className: styles.title,
        style: {
          marginBottom: '8px'
        }
      }, intl.get('cpfm.individual.view.message.title.ruleCode').d('规则代码')), /*#__PURE__*/React.createElement("div", {
        className: styles['code-container']
      }, /*#__PURE__*/React.createElement(FormItem, null, form.getFieldDecorator('renderRule', {
        initialValue: rule
      })( /*#__PURE__*/React.createElement(TextArea, {
        ref: function ref(_ref3) {
          _this3.textArea = _ref3;
        },
        className: styles['code-text-area'],
        placeholder: htmlText,
        trimAll: true,
        onChange: this.openList,
        onClick: this.closeList
      }))), /*#__PURE__*/React.createElement("div", {
        className: styles['text-area-compute-offset'],
        ref: this.hiddenDiv
      }), this.renderList()))));
    }
  }]);

  return _class3;
}(React.Component), (_applyDecoratedDescriptor(_class3.prototype, "onOk", [_dec2], Object.getOwnPropertyDescriptor(_class3.prototype, "onOk"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "openList", [_dec3], Object.getOwnPropertyDescriptor(_class3.prototype, "openList"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "closeList", [_dec4], Object.getOwnPropertyDescriptor(_class3.prototype, "closeList"), _class3.prototype), _applyDecoratedDescriptor(_class3.prototype, "fillFromTipsList", [_dec5], Object.getOwnPropertyDescriptor(_class3.prototype, "fillFromTipsList"), _class3.prototype)), _class3)) || _class2);

export { _class as default };